<template>
  <aside class="hot-list">
    <div v-if="isAuthenticated" class="if">
      <div class="header">
        <el-upload
          class="avatar-uploader"
          action="/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <el-avatar :size="64" :src="userData.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"></el-avatar>
        </el-upload>
        <div class="text-container">
          <div class="greeting">{{ userData.username }}</div>
          <div class="subtitle">欢迎回来，开启您的花艺之旅</div>
        </div>
      </div>
    </div>
    <div v-else class="if">
      <div class="header">
        <el-avatar :size="64" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
        <div class="text-container">
          <div class="greeting">下午好</div>
          <div class="subtitle">欢迎光临花之语</div>
        </div>
      </div>
      <el-button type="danger" class="cta-button" @click="goToLogin">立即登录</el-button>
    </div>


    <div class="links">
      <div class="link-item" @click="handleNavigation('/orders')">
        <div class="link-icon">
          <i class="el-icon-document"></i>
        </div>
        <div class="link-text">
          <span class="link-title">我的账单</span>
          <span class="link-desc">查看订单记录</span>
        </div>
      </div>
      <div class="link-item" @click="handleNavigation('/logistics')">
        <div class="link-icon">
          <i class="el-icon-truck"></i>
        </div>
        <div class="link-text">
          <span class="link-title">我的物流</span>
          <span class="link-desc">追踪配送状态</span>
        </div>
      </div>
      <div class="link-item" @click="handleNavigation('/favorites')">
        <div class="link-icon">
          <i class="el-icon-star-off"></i>
        </div>
        <div class="link-text">
          <span class="link-title">宝贝收藏</span>
          <span class="link-desc">收藏的商品</span>
        </div>
      </div>
      <div class="link-item" @click="handleNavigation('/coupons')">
        <div class="link-icon">
          <i class="el-icon-tickets"></i>
        </div>
        <div class="link-text">
          <span class="link-title">我的优惠券</span>
          <span class="link-desc">优惠券管理</span>
        </div>
      </div>
    </div>

    
    <!-- AI助手部分 -->
    <div class="ai-assistant" :class="{ 'fullscreen': isFullscreen }">
      <div class="ai-header">
        <div class="header-left">
          <span>AI花艺助手</span>
        </div>
        <div class="header-right">
          <i :class="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'" 
             @click="toggleFullscreen"
             class="fullscreen-icon"></i>
        </div>
      </div>
      <div class="chat-container" ref="chatContainer">
        <div v-for="(message, index) in chatMessages" :key="index" 
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
      <div class="input-container">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="2"
          placeholder="请输入您的问题..."
          @keyup.enter.native="sendMessage"
          :disabled="isLoading">
        </el-input>
        <el-button type="primary" @click="sendMessage" :loading="isLoading" 
          :disabled="!userInput.trim() || isLoading">
          发送
        </el-button>
      </div>
    </div>
  </aside>
</template>

<script>
export default {
  name: 'UserHotList',
  data() {
    return {
      isAuthenticated: false,
      userData: {},
      userInput: '',
      chatMessages: [],
      isLoading: false,
      isFullscreen: false
    };
  },
  created() {
    this.loadUserInfo();
  },
  methods: {
    logout() {
      this.isAuthenticated = false;
      localStorage.removeItem('token'); // 清除token
      this.$router.push('/login');
    },
    loadUserInfo() {
      this.request.get("/users/info").then(res => {
        if (res.code === 1) {
          this.userData = res.data;
          this.isAuthenticated = true;
        } else {
          this.isAuthenticated = false;
        }
      }).catch(err => {
        console.error('Failed to load user info', err);
        this.isAuthenticated = false;
      });
    },
    goToLogin() {
      this.$router.push('/login');
    },
    handleNavigation(path) {
      if (!this.isAuthenticated) {
        this.$message({
          message: '请先登录后再操作',
          type: 'warning'
        });
        setTimeout(() => {
          this.goToLogin();
        }, 1500);
        return;
      }
      this.$router.push(path);
    },
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;

      const userMessage = this.userInput.trim();
      this.chatMessages.push({
        role: 'user',
        content: userMessage
      });

      this.userInput = '';
      this.isLoading = true;

      try {
        const response = await this.request.post("/ai/chat", {
          messages: this.chatMessages
        });

        // 直接添加返回的数据作为AI回复
        this.chatMessages.push({
          role: 'assistant',
          content: response.data
        });
      } catch (error) {
        console.error('AI请求失败:', error);
        this.$message.error('网络错误，请重试');
      } finally {
        this.isLoading = false;
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    scrollToBottom() {
      const container = this.$refs.chatContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      if (this.isFullscreen) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    handleAvatarSuccess(res) {
      // 更新用户头像
      this.request.post('/users/update/avatar', {
        avatarUrl: res.data
      }).then(response => {
        if (response.code === 1) {
          this.$message.success('头像更新成功');
          this.loadUserInfo(); // 重新加载用户信息
        } else {
          this.$message.error(response.msg || '头像更新失败');
        }
      }).catch(err => {
        console.error('更新头像失败:', err);
        this.$message.error('更新头像失败，请重试');
      });
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB！');
        return false;
      }
      return true;
    }
  }
};
</script>

<style scoped>
.hot-list {
  background-color: white;
  padding: 20px;
  margin-right: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(to right, #fff5f5, #fff);
  border-radius: 8px;
}

.text-container {
  margin-left: 20px;
}

.greeting {
  font-size: 1.5em;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.subtitle {
  color: #666;
  font-size: 0.9em;
}

.cta-button {
  width: 100%;
  padding: 12px 0;
  font-size: 1.1em;
  font-weight: 500;
  border-radius: 8px;
  margin: 15px 0;
  transition: all 0.3s ease;
}

.cta-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 74, 74, 0.2);
}

.links {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin: 25px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 12px;
  flex: 0 0 auto;
}

.link-item {
  display: flex;
  align-items: center;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.link-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 74, 74, 0.15);
  background: linear-gradient(to right, #fff5f5, #fff);
}

.link-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff5f5;
  border-radius: 10px;
  margin-right: 12px;
}

.link-icon i {
  font-size: 24px;
  color: #ff4a4a;
}

.link-text {
  display: flex;
  flex-direction: column;
}

.link-title {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
}

.link-desc {
  font-size: 12px;
  color: #999;
}

.promotion {
  position: relative;
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.promotion img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.promotion:hover img {
  transform: scale(1.05);
}

.promotion-text {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: white;
  font-size: 1.2em;
  text-align: center;
}

.ai-assistant {
  flex: 1;
  margin: 20px 0 0 0;
  display: flex;
  flex-direction: column;
  min-height: 300px;
  max-height: 50vh;
}

.ai-assistant.fullscreen {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  z-index: 10;
  max-height: none;
}

.ai-header {
  padding: 8px 15px;
  background: linear-gradient(to right, #409EFF, #36cfc9);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-right {
  cursor: pointer;
}

.fullscreen-icon {
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.3s ease;
  padding: 5px;
}

.fullscreen-icon:hover {
  transform: scale(1.1);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f5f5f5;
}

.message {
  margin-bottom: 8px;
  max-width: 80%;
}

.user-message {
  align-items: flex-end;
  padding-left: 20%;
}

.ai-message {
  align-items: flex-start;
  padding-right: 20%;
}

.message-content {
  padding: 8px 12px;
  font-size: 14px;
}

.user-message .message-content {
  background: #409EFF;
  color: #000;
  border-radius: 16px 0 16px 16px;
  margin-right: 10px;
}

.ai-message .message-content {
  background: white;
  color: #000;
  border-radius: 0 16px 16px 16px;
  margin-left: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.input-container {
  padding: 10px;
  background: white;
  border-top: 1px solid #eee;
}

.input-container .el-input textarea {
  max-height: 60px;
}

.input-container .el-button {
  width: 80px;
  height: 40px;
  align-self: flex-end;
}

/* 滚动条样式 */
.chat-container::-webkit-scrollbar {
  width: 6px;
}

.chat-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-track {
  background: transparent;
}

/* 添加平滑过渡 */
.ai-assistant {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .ai-assistant.fullscreen {
    top: 5%;
    left: 5%;
    right: 5%;
    bottom: 5%;
  }
  
  .user-message {
    padding-left: 10%;
  }
  
  .ai-message {
    padding-right: 10%;
  }
  
  .message {
    max-width: 85%;
  }

  .links {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }

  .link-item {
    padding: 10px;
  }

  .link-icon {
    width: 32px;
    height: 32px;
  }

  .link-icon i {
    font-size: 20px;
  }
}

/* 添加反馈相关样式 */
.feedback-uploader {
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}

.el-dialog__body {
  padding: 20px 30px;
}

.avatar-uploader {
  cursor: pointer;
}

.avatar-uploader:hover .el-avatar {
  transform: scale(1.05);
  transition: all 0.3s ease;
}

.el-avatar {
  transition: all 0.3s ease;
}
</style>